<template>
	<evaluate-info v-if="isNotNull(targetsData) && targetsData.length>0" ref="evaluateRef" :target-data="targetsData"
		:comments-data="commentsData"></evaluate-info>
</template>

<script>
	import {
		deepClone,
		isNotNull
	} from "@/utils/common.js"
	import {
		getTargetDetail,
		saveComments,
		uploadUrl
	} from "@/api/supervise/index.js"

	export default {
		data() {
			return {
				isNotNull,
				queryData: {},
				targetsData: [],
				commentsData: [],
				uploadUrl,
				storageKey: ''
			}
		},
		methods: {
			getTargetDetail() {
				uni.getStorage({
					key: this.storageKey,
					success: (res) => {
						console.log("success")
						const data = deepClone(res.data);
						let commentsData = []
						let targetsData = []
						data.forEach(item => {
							if (item.comment) {
								let comment = deepClone(item.comment);
								comment.targetId = item.comment.targetId || item.id
								if (comment.storeageFiles && comment.storeageFiles.length > 0) {
									const imageFiles = comment.storeageFiles.filter(item => {
										return item.type === 'image'
									}).map(item => {
										let url = item.url;
										const name = url.split("/");
										const fileName = name[name.length - 1];
										return {
											url: url,
											name: fileName,
											extname: fileName.split(".")[1]
										};
									})
									const voiceFiles = comment.storeageFiles.filter(item => {
										return item.type === 'voice'
									}).map(item => {
										let url = item.url;
										const name = url.split("/");
										const fileName = name[name.length - 1];
										return {
											url: url,
											name: fileName,
											extname: fileName.split(".")[1]
										};
									})
									const videoFiles = comment.storeageFiles.filter(item => {
										return item.type === 'video'
									}).map(item => {
										let url = item.url;
										const name = url.split("/");
										const fileName = name[name.length - 1];
										return {
											url: url,
											name: fileName,
											extname: fileName.split(".")[1]
										};
									})
									this.$store.commit('SAVE_PIC', {
										uuid: comment.uuid,
										files: {
											originFiles: [],
											appendFiles: imageFiles
										}
									})
									this.$store.commit('SAVE_VIDEO', {
										uuid: comment.uuid,
										files: {
											originFiles: [],
											appendFiles: videoFiles
										}
									})
									this.$store.commit('SAVE_VOICE', {
										uuid: comment.uuid,
										files: {
											originFiles: [],
											appendFiles: voiceFiles
										}
									});
								}
								commentsData.push(comment);
								delete item.comment;
							}
							targetsData.push(item)
						})
						this.targetsData = targetsData;
						this.commentsData = commentsData;
					},
					fail: (err) => {
						console.log("fail");
						const params = {
							targetId: this.queryData.id,
							finishState: this.queryData.finishState,
							createTime: this.queryData.createTime,
							activityId: this.queryData.activityId,
							schoolId: this.queryData.schoolId
						};
						getTargetDetail(params).then(res => {
							this.targetsData = res.targets;
							this.commentsData = res.comments;
						});
					}
				});

			},
			async saveFile(files) {
				const saveFiles = deepClone(files);
				let newFiles = [];
				return new Promise((resolve, reject) => {
					if (saveFiles) {
						saveFiles.forEach(async (file, fileIndex) => {
							await uni.saveFile({
								tempFilePath: file.url,
								success: function(res) {
									plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
											newFiles.push({
												type: file.type,
												url: fs.root.fullPath + (res.savedFilePath.replace("_doc/", ""))
											})
											if (fileIndex === saveFiles.length - 1) {
												resolve(newFiles);
											}
										},
										function(e) {
											console.log(
												"Request file system failed: " +
												e.message);
											uni.$u.toast("实证材料保存失败");
											return;
										});
								}
							});
						})
					} else {
						resolve()
					}
				});
			},
			saveStore(data) {
				//先判断是否已经有缓存，有的话先删除
				const storeageValue = uni.getStorageSync(this.storageKey);
				if (storeageValue) {
					uni.removeStorageSync(this.storageKey);
				}
				new Promise((resolve, reject) => {
					data.forEach(async (item, index) => {
						const comment = item.comment;
						if (comment.storeageFiles && comment.storeageFiles.length > 0) {
							await this.saveFile(comment.storeageFiles)
								.then(res => {
									const newFiles = res;
									comment.storeageFiles = newFiles;
								});
						}
						if (index === data.length - 1) {
							resolve(data);
						}
					});
				}).then(storeageData => {
					uni.setStorage({
						key: this.storageKey,
						data: storeageData,
						success: function() {
							console.log('success');
							uni.$u.toast("提交成功")
						}
					});
				});
			},
			submit() {
				const that = this;
				const ref = this.$refs.evaluateRef;
				ref.validate(({
					valid,
					error,
					formData,
					originalData
				}) => {
					if (valid) {
						uni.getNetworkType({
							success: (res) => {
								if (res.networkType === 'none') { //网络不通，缓存在本地
									this.saveStore(originalData)
								} else { // 提交服务器
									const data = deepClone(formData)
									new Promise((resolve, reject) => {
										let saveData = [];
										data.forEach(async (item, index) => {
											if (item.files && item.files.length >
												0) {
												await this.uploadFile(item.files)
													.then(res => {
														const newData = {
															...item,
															activityId: this.queryData.activityId,
															schoolId: this.queryData.schoolId,
															urlId: res
														};
														delete newData.files;
														saveData.push(newData);
													});
											} else {
												const newData = {
													...item,
													activityId: this.queryData.activityId,
													schoolId: this.queryData.schoolId,
												};
												delete newData.files;
												saveData.push(newData);
											}
											if (index === formData.length - 1) {
												resolve(saveData);
											}
										});
									}).then(comments => {
										saveComments(JSON.stringify(comments)).then(res => {
											uni.$u.toast(res.result);
											this.getTargetDetail();
											const storeageValue = deepClone(uni.getStorageSync(this.storageKey));
											if (storeageValue) {
												storeageValue.forEach(async (item, index) => {
													const comment = item.comment;
													if (comment.storeageFiles && comment.storeageFiles.length > 0) {
														comment.storeageFiles.forEach(async (file, fileIndex) => {
															uni.removeSavedFile({
																filePath: file.url,
																complete: function(res) {
																	console.log(res);
																}
															});
														});
													}
												});
												uni.removeStorageSync(this.storageKey);
											}

										})
									});
								}
							}
						});

					} else {
						uni.$u.toast('还存在必填项未填写');
						return;
					}

				})

				return;

			},
			async uploadFile(files) {
				const saveFiles = deepClone(files);
				let urlId = [];
				return new Promise((resolve, reject) => {
					console.log("开始上传")
					if (saveFiles) {
						const length = saveFiles.length;
						saveFiles.forEach((file, index) => {
							uni.uploadFile({
								url: this.uploadUrl,
								files: [file],
								success: (res) => {
									if (res.statusCode === 200) {
										const resData = JSON.parse(res
											.data);
										urlId = [
											...urlId,
											...resData.urlId
										]
										if (urlId.length === length) {
											resolve(urlId)
										}
									} else {
										uni.$u.toast("实证材料上传失败");
									}
								},
								fail: (err) => {
									console.log(err)
									uni.$u.toast("实证材料上传失败");
									resolve1("");
								}
							})
						});
					} else {
						resolve()
					}
				});
			},
		},
		onLoad: function(option) {
			const queryData = JSON.parse(decodeURIComponent(option.queryData));
			this.queryData = queryData;
			uni.setNavigationBarTitle({
				title: queryData.name
			});
			let deviceId = uni.getStorageSync("deviceId");
			// key = deviceId_userName_activityId_targetId_schoolId
			this.storageKey =
				`${deviceId}_${this.$store.state.user.name}_${this.queryData.activityId}_${this.queryData.id}_${this.queryData.schoolId}`;
			this.getTargetDetail();
		},
		onNavigationBarButtonTap(e) {
			// 点击导航栏自定义按钮
			this.submit()
		}
	}
</script>

<style lang="scss" scoped>
</style>